package com.hdd.biz.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hdd.biz.app.dto.*;
import com.hdd.biz.app.entity.FansCountModel;
import com.hdd.biz.app.entity.PaintingWorksModel;
import com.hdd.biz.app.entity.UserCenterModel;
import com.hdd.biz.app.mapper.APPPaintingWorksMapper;
import com.hdd.biz.app.service.PublishService;
import com.hdd.biz.app.service.UserCenterService;
import com.hdd.biz.member.entity.Member;
import com.hdd.biz.member.mapper.MemberMapper;
import com.hdd.biz.painting.entity.PaintingWorks;
import com.hdd.biz.painting.mapper.PaintingWorksMapper;
import com.hdd.biz.painting.mapper.UserFollowMapper;
import com.hdd.biz.painting.service.FavourService;
import com.hdd.biz.painting.service.PaintingWorksService;
import com.hdd.biz.painting.service.UserFollowService;
import com.hdd.utils.JsonUtil;
import com.hdd.utils.SensitiveWordBiz;
import com.hdd.utils.wx.RedisUtil;
import com.hdd.utils.wxEncrypt.WXCore;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class UserCenterServiceImpl implements UserCenterService {

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private PaintingWorksService paintingWorksService;
    @Autowired
    private PaintingWorksMapper paintingWorksMapper;
    @Autowired
    private APPPaintingWorksMapper appPaintingWorksMapper;
    @Autowired
    private UserFollowMapper userFollowMapper;
    @Autowired
    private UserFollowService userFollowService;
    @Autowired
    private FavourService favourService;
    @Autowired
    private PublishService publishService;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public AppResponse userInfo(AppRequest request) {
        AppResponse res = new AppResponse();
        UserCenterModel ucm = new UserCenterModel();
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id",request.getUserId());
        Member member =  memberMapper.selectOne(wrapper);
        if(member==null){
         res.setCode(-1000);
         res.setMessage("用户信息不存在");
         return res;
        }

        ucm.setNick(member.getNickname());
        ucm.setBirthday(member.getBirthday());
        ucm.setProvince(member.getProvince());
        ucm.setArea(member.getArea());
        ucm.setSchool(member.getSchool());
        ucm.setProfession(member.getProfession());
        ucm.setCity(member.getCity());
        ucm.setPhone(member.getPhone());
        ucm.setSex(member.getSex());
        ucm.setUserCode(member.getPaintingNum());
        ucm.setDescription(member.getDescription());
        ucm.setHeadImgUrl(member.getHeadImgUrl());
        ucm.setBeLiked(paintingWorksService.beLikeds(request.getUserId()));
        ucm.setFollow(userFollowService.followsCount(request.getUserId(),request.getUserId()));
        ucm.setFans(userFollowService.fansCount(request.getUserId(),request.getUserId()));
        if(redisUtil.hasKey("followUser:"+request.getUserId())){
            ucm.setNewFans(redisUtil.get("followUser:"+request.getUserId()).toString());
        }else{
            ucm.setNewFans("0");
        }
        ucm.setViews(paintingWorksService.views(request.getUserId()));
        ucm.setDrafts(paintingWorksService.getDrafts(request.getUserId()));
        res.setItem(ucm);
        return res;
    }


    @Override
    public Member getUser(String userId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id",userId);
        return memberMapper.selectOne(wrapper);
    }

    @Override
    public AppResponse uploadAvatar(UploadAvatarRequest request) {
        AppResponse res = new AppResponse();
        Member member = new Member();
        member.setHeadImgUrl(request.getAvatar());
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",request.getUserId());
        memberMapper.update(member,wrapper);
        return res;
    }


    @Override
    public AppResponse updateUserInfo(InfoEditorRequest request) {
        AppResponse res = new AppResponse();
        Member member = new Member();
        member.setUserId(request.getUserId());

        member.setNickname(request.getNick());

        if(StringUtils.isNotEmpty(request.getNick())){
            SensitiveWordBiz wordInit = new SensitiveWordBiz();
            Set<String> source = new HashSet<>();
            source.add("画多多");
            source.add("画多");
            Map map = wordInit.addSensitiveWordToHashMap(source);
            boolean result = wordInit.containSensitiveWord(request.getNick(), map);
            if(result){
                res.setCode(-1000);
                res.setMessage("涉及敏感词,请修改昵称~");
                return res;
            }

        }
        member.setDescription(request.getDescription());
        member.setBirthday(request.getBirthday());
        member.setSex(request.getSex());
        member.setProvince(request.getProvince());
        member.setCity(request.getCity());
        member.setArea(request.getArea());
        member.setSchool(request.getSchool());
        member.setProfession(request.getProfession());
        QueryWrapper<Member> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",request.getUserId());
        memberMapper.update(member,wrapper);
        return res;
    }


    @Override
    public AppResponse myWorksList(MyWorksRequest request) {
        AppResponse response = new AppResponse();
        QueryWrapper<PaintingWorks> wrapper = new QueryWrapper();
        Page<PaintingWorks> pages = new Page<>(request.getPageNo(),request.getPageSize());
        wrapper.eq("user_id",request.getUserId());
        wrapper.eq("del_flag",0);
        wrapper.ge("shows",1);
        wrapper.eq("wiki_id",1);

        wrapper.orderByDesc("create_time");
        IPage<PaintingWorks> mapIPage = paintingWorksMapper.selectPage(pages, wrapper);
        List<PaintingWorks> agents = mapIPage.getRecords();
        response.setItems(convertWorks(agents,request.getUserId()));
        response.setTotals(mapIPage.getTotal());
        return response;
    }

    @Override
    public AppResponse myLikeList(MyWorksRequest request) {
        AppResponse response = new AppResponse();
        Map<String,Object> map = new HashMap<>();
        map.put("pageNo",(request.getPageNo()-1)*request.getPageSize());
        map.put("pageSize",request.getPageSize());
        map.put("userId",request.getUserId());
        response.setItems(convertWorks(appPaintingWorksMapper.myLikeList(map),request.getUserId()));
        return response;
    }


    @Override
    public AppResponse preferList(MyWorksRequest request) {
        AppResponse response = new AppResponse();
        Map<String, Object> map = new HashMap<>();
        map.put("pageNo", (request.getPageNo() - 1) * request.getPageSize());
        map.put("pageSize", 1000);
        map.put("userId", request.getUserId());
        List<PaintingWorksModel> list = convertWorks(appPaintingWorksMapper.myLikeList(map), request.getUserId());
        redisUtil.del("likeList:" + request.getUserId());
        int a = 1;
        for (PaintingWorksModel p : list) {
            p.setIndex(a);
            a = a + 1;
            redisUtil.lSet("likeList:" + request.getUserId(), JsonUtil.toJsonString(p));
        }

        response.setItems(list);
        return response;
    }


    @Override
    public AppResponse preferSelect(MyWorksRequest request) {
        AppResponse response = new AppResponse();
        if(request.getIndex()<0){
            return response;
        }
        if(redisUtil.hasKey("likeList:"+request.getUserId())){
            List<Object> objecs = new ArrayList<>();
            objecs.add(redisUtil.lGetIndex("likeList:"+request.getUserId(),request.getIndex()-1));
            response.setItems(objecs);
        }
        return response;
    }

    @Override
    public AppResponse preferDown(MyWorksRequest request) {
        AppResponse response = new AppResponse();
        if(redisUtil.hasKey("likeList:"+request.getUserId())){

            if(request.getIndex()<=1){
                return response;
            }

            List<Object> list1 = redisUtil.lGet("likeList:"+request.getUserId(),
                    (request.getIndex()-request.getPageSize()<=0)?0:(request.getIndex()-request.getPageSize()),request.getIndex()-2);
            response.setItems(list1);
        }
        return response;
    }

    @Override
    public AppResponse preferUp(MyWorksRequest request) {

        AppResponse response = new AppResponse();
        if(redisUtil.hasKey("likeList:"+request.getUserId())){
            Long size = redisUtil.lGetListSize("likeList:"+request.getUserId());
            if(request.getIndex()>size){
                return response;
            }
            List<Object> list2 = redisUtil.lGet("likeList:"+request.getUserId(),request.getIndex(),
                    (request.getIndex()+request.getPageSize())>=size?size:(request.getIndex()+request.getPageSize()));
            response.setItems(list2);
        }
        return response;
    }


    @Override
    public AppResponse bindPhone(BindPhoneRequest request) {
        AppResponse response = new AppResponse();
        String sessionKey = redisUtil.get("sessionKey:"+request.getUserId()).toString();
        if("F".equals(request.getReject())){
            return response;
        }
        String json =  WXCore.decrypt("wx59c864c7d2fc6536",request.getData(),sessionKey,request.getIv());
        String phone = JSONObject.parseObject(json).getString("phoneNumber");
        if(phone!=null){
            Member member = new Member();
            member.setPhone(phone);
            member.setUserId(request.getUserId());
            QueryWrapper<Member> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",request.getUserId());
            memberMapper.update(member,wrapper);
        }
        return response;
    }


    @Override
    public AppResponse myWikiList(MyWorksRequest request) {
        AppResponse response = new AppResponse();
        QueryWrapper<PaintingWorks> wrapper = new QueryWrapper();
        Page<PaintingWorks> pages = new Page<>(request.getPageNo(),request.getPageSize());
        wrapper.eq("user_id",request.getUserId());
        wrapper.eq("del_flag",0);
        wrapper.ge("shows",1);
        wrapper.gt("wiki_id",1);
        wrapper.orderByDesc("create_time");
        IPage<PaintingWorks> mapIPage = paintingWorksMapper.selectPage(pages, wrapper);
        List<PaintingWorks> agents = mapIPage.getRecords();
        response.setTotals(mapIPage.getTotal());
        response.setItems(convertWorks(agents,request.getUserId()));
        return response;
    }



    /**
     * 作品对象转换
     * @param works
     * @return
     */
    public List<PaintingWorksModel> convertWorks(List<PaintingWorks> works,String userId){
        List<PaintingWorksModel> list = new ArrayList<>();
        PaintingWorksModel worksModel = null;
        QueryWrapper<Member> memberQueryWrapper = null;
        Member member = null;
        for(PaintingWorks p:works){
            worksModel = new PaintingWorksModel();
            worksModel.setId(p.getId());
            worksModel.setUserId(p.getUserId());
            worksModel.setPainting(p.getPainting());
            worksModel.setPaintingNo(p.getPaintingNo());
            worksModel.setAllowReward(p.getAllowReward());
            worksModel.setPaintingName(p.getPaintingName());
            worksModel.setVisitCount(p.getVisitCount());
            worksModel.setMediaTime(p.getMediaTime());
            worksModel.setPaintingDescription(p.getPaintingDescription());
            worksModel.setPraiseCount(p.getVisitCount());
            worksModel.setRewardCount(p.getRewardCount());
            worksModel.setFavourCount(p.getFavourCount());
            worksModel.setWikiId(p.getWikiId());
            worksModel.setDraftInfo(null);
            memberQueryWrapper = new QueryWrapper<>();
            memberQueryWrapper.eq("user_id",p.getUserId());
            member = memberMapper.selectOne(memberQueryWrapper);
            if(member!=null){
                worksModel.setHeadImgUrl(member.getHeadImgUrl());
                worksModel.setNickName(member.getNickname());
            }
            worksModel.setReshipmentCount(p.getReshipmentCount());
            if(!StringUtils.isEmpty(userId)){
                worksModel.setTopics(publishService.getTopicsByWorkId(p.getId()));
                worksModel.setUserFollow(userFollowService.isFollow(userId,p.getUserId()));
                worksModel.setFollow(favourService.isFavour(userId,p.getId()));
            }

            worksModel.setShareCount(p.getShareCount());
            list.add(worksModel);
        }
        return list;
    }

    @Override
    public AppResponse fans(FansRequest request) {
        AppResponse response = new AppResponse();
        Map<String,Object> map = new HashMap<>();
        map.put("pageNo",(request.getPageNo()-1)*request.getPageSize());
        map.put("pageSize",request.getPageSize());
        map.put("userId",request.getUserId());
        List<Member> list = userFollowMapper.myFans(map);
        for(Member m:list){
            m.setMutualFollow(userFollowService.mutualFollow(request.getUserId(),m.getUserId()));
        }
        response.setItems(list);
        return response;
    }

    @Override
    public AppResponse follow(FansRequest request) {
        AppResponse response = new AppResponse();
        Map<String,Object> map = new HashMap<>();
        map.put("pageNo",(request.getPageNo()-1)*request.getPageSize());
        map.put("pageSize",request.getPageSize());
        map.put("userId",request.getUserId());
        List<Member> list = userFollowMapper.myFollows(map);
        for(Member m:list){
            m.setMutualFollow(userFollowService.mutualFollow(m.getUserId(),request.getUserId()));
        }
        response.setItems(list);
        return response;
    }

    @Override
    public AppResponse followTotal(FansRequest request) {
        AppResponse response = new AppResponse();
        FansCountModel fansCountModel = new FansCountModel();

        fansCountModel.setFans(userFollowService.fansCount(request.getUserId(),request.getUserId()));
        fansCountModel.setFollows( userFollowService.followsCount(request.getUserId(),null));
        //TODO 草稿箱列表
        response.setItem(fansCountModel);
        return response;
    }


    @Override
    public AppResponse drafts(FansRequest request) {
        AppResponse response = new AppResponse();
        QueryWrapper<PaintingWorks> wrapper = new QueryWrapper();
        Page<PaintingWorks> pages = new Page<>(request.getPageNo(),request.getPageSize());
        wrapper.eq("user_id",request.getUserId());
        wrapper.eq("shows",0);
        wrapper.eq("del_flag",0);
        wrapper.orderByDesc("create_time");
        IPage<PaintingWorks> mapIPage = paintingWorksMapper.selectPage(pages, wrapper);
        List<PaintingWorks> agents = mapIPage.getRecords();
        response.setItems(convertWorks(agents,request.getUserId()));
        return response;
    }


    @Override
    public AppResponse delDrafts(WorksInfoRequest request) {
        AppResponse response = new AppResponse();

        String ids[] = request.getWorksId().split(",");
        PaintingWorks paintingWorks = null;
        QueryWrapper<PaintingWorks> wrapper = null;
        for(int i=0;i<ids.length;i++){
            paintingWorks = new PaintingWorks();
            paintingWorks.setId(ids[i]);
            paintingWorks.setDelFlag(1);
            paintingWorks.setShows(1);
            wrapper = new QueryWrapper<>();
            wrapper.eq("id",ids[i]);
            paintingWorksMapper.update(paintingWorks,wrapper);
        }
        return response;
    }

    @Override
    public AppResponse worksTotal(FansRequest request) {
        AppResponse response = new AppResponse();
        FansCountModel fansCountModel = new FansCountModel();
        fansCountModel.setWorks(paintingWorksService.works(request.getUserId()));
        fansCountModel.setLikes(favourService.favours(request.getUserId()));
        fansCountModel.setWiki(paintingWorksService.wikis(request.getUserId()));
        response.setItem(fansCountModel);
        return response;
    }


    @Override
    public AppResponse allowReward(WorksInfoRequest request) {
        AppResponse response = new AppResponse();
        PaintingWorks paintingWorks =  paintingWorksService.findWorksById(request.getWorksId());
        if(paintingWorks!=null){
            if(paintingWorks.getAllowReward()>0){
                paintingWorks.setAllowReward(0);
            }else{
                paintingWorks.setAllowReward(1);
            }
            QueryWrapper<PaintingWorks> wrapper = new QueryWrapper<>();
            wrapper.eq("id",request.getWorksId());
            paintingWorksMapper.update(paintingWorks,wrapper);
        }
        return response;
    }


    @Override
    public AppResponse isFollow(WorksInfoRequest request) {
        AppResponse response = new AppResponse();

        if(StringUtils.isEmpty(request.getUserId())){
            response.setMessage("未关注");
            response.setCode(-1000);
            return response;
        }

        if(userFollowService.isFollow(request.getUserId(),request.getAuthorId())){
            response.setMessage("已关注");
        }else{
            response.setMessage("未关注");
            response.setCode(-1000);
        }
        return response;
    }
}
